layui.use(['jquery', 'form', 'layer'], function () {
  var $ = layui.jquery,
    form = layui.form,
    layer = layui.layer;

  form.on('submit(doSub)', function (data) {
    $.ajax({
      type: 'POST',
      url: data.form.action,
      data: data.field,
      dataType: "json",
      success: function (res) {
        if (res.code === 200) {
          layer.msg(res.msg, {icon: 1, time: 2000}, function () {
            window.location.reload();
          })
        } else {
          layer.msg(res.msg, {icon: 2, time: 2000})
        }
      }
    });
    return false;
  });

  //监听图片选择弹窗打开
  $('body').on('click', '[data-open-pic]', function () {
    ShowPicList(this);
  });

  // 监听弹出层的打开
  $('body').on('click', '[data-open]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-open');
    let reload = $(this).attr('data-reload');
    let w = $(this).attr('data-width');
    let h = $(this).attr('data-height');
    HuiAdminShow(title, url, w, h, reload);
  });

  $('body').on('click', '[data-open-full]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-open-full');
    let reload = $(this).attr('data-reload');
    HuiAdminOpenFull(title, url, reload);
  });

  $('body').on('click', '[data-confirm]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-confirm');
    let reload = $(this).attr('data-reload');
    HuiAdminConfirm(url, title, reload);
  });

  $('body').on('click', '[data-delete]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-delete');
    let reload = $(this).attr('data-reload');
    HuiAdminDel(url, title, reload);
  });

  /* 监听状态设置开关 */
  form.on('switch(switchStatus)', function (data) {
    var that = $(this),
      status = 0;
    if (!that.attr('data-href')) {
      layer.msg('请设置data-href参数');
      return false;
    }
    if (this.checked) {
      status = 1;
    }
    $.post(that.attr('data-href'), {
      val: status
    }, function (res) {
      if (res.code === 1 || res.code === 200) {
        layer.msg(res.msg, {time: 1500, icon: 1}, function () {
          if (res.data.refresh == 1) {
            window.parent.location.reload();
          } else if (res.data.refresh == 2) {
            window.location.reload();
          }
        });
      } else {
        layer.msg(res.msg, {time: 1500, icon: 2}, function () {
          that.trigger('click');
          form.render('checkbox');
        });
      }
    });
  });

  window.getCaptCha = function () {
    $.post("/admin/login/captcha", {}, function (res) {
      if (res.code === 200) {
        $('#captcha_src').attr('src', res.data.src)
        $('#uniqId').val(res.data.uniqid)
      }
    })
  }

  /*满屏（全屏）打开窗口*/
  window.HuiAdminOpenFull = function (title, url, reload = 0) {
    $.get(url, function (res) {
      var index = layer.open({
        type: 2,
        title: title,
        content: url,
        skin: 'skin-layer-hui',
        closeBtn: 11,
        end: function () {
          if (reload == 1) {
            window.parent.location.reload();
          } else if (reload == 2) {
            window.location.reload();
          }
        }
      });
      layer.full(index);
    });
  }

  /*
   * @todo 弹出层，弹窗方法
   * layui.use 加载layui.define 定义的模块，当外部 js 或 onclick调用 use 内部函数时，需要在 use 中定义 window 函数供外部引用
   * http://blog.csdn.net/xcmonline/article/details/75647144
   */
  /*
      参数解释：
      title   标题
      url     请求的url
      id      需要操作的数据id
      w       弹出层宽度（缺省调默认值）
      h       弹出层高度（缺省调默认值）
  */

  window.ShowPicList = function (element) {
    var url = $(element).data('open-pic');
    if (!arguments.callee.hWnd || arguments.callee.hWnd.closed) {
      arguments.callee.hWnd = window.open(url, 'ckeditor', ' toolbar=no, menubar=no, resizable=no,location=no, status=no, fullscreen=no, width=' + Math.floor(window.screen.availWidth * 0.8) + ', height=' + Math.floor(window.screen.availHeight * 0.7) + ', left=' + Math.floor(window.screen.availWidth * 0.1) + ', top=' + Math.floor(window.screen.availHeight * 0.15) + '');
    }
    arguments.callee.hWnd.focus();
    window['ckeditor_select_callback'] = function (url, type, input_select_id) {
      if (!url) {
        return false;
      }
      var input = $(element).closest('.huicmf-upload').find('#' + input_select_id)[0];
      if (type === 'one') {
        $(input).val(url);
      } else {
        var str = "";
        var i1 = 0;
        var getItemLength = parseInt($(input).find('.file-item').length);
        var length = GV.site.pic_more_nums;

        $.each(url, function (i, val) {
          let find = $(input).find('.file-item-id-' + val.file_id).html();
          if (typeof (find) === 'undefined') {
            i1 += 1;
            str += ' <div class="file-item file-item-id-' + val.file_id + '">\n' +
              '    <img src="' + val.file_path + '">\n' +
              '    <input type="hidden" name="params[thumbs][]" value="' + val.file_path + '">\n' +
              '    <i class="layui-icon layui-icon-close file-item-delete" onclick="fileItemDelete(' + val.file_id + ')"></i>\n' +
              '</div>';
          }
        })
        var check_length = i1;
        if (length > 1 && length < (check_length + getItemLength)) {
          layer.msg('文件最大同时选择数为：' + length, {
            icon: 2
          });
          return false;
        }
        $(input).append(str);
        $(input).attr('data-nums', (check_length + getItemLength));
      }

    }
  }

  window.HuiAdminShow = function (title, url, w, h, reload = 0) {
    if (title == null || title == '') {
      title = false;
    }
    if (url == null || url == '') {
      url = "404.html";
    }
    if (w == null || w == '') {
      w = $(window).width() * 0.45;
    }

    parent.layui.drawer.open({
      legacy: false,
      title: [title, 'font-size:16px;color:#2d8cf0'],
      offset: 'r',
      area: w + 'px',
      closeBtn: 1,
      zIndex: parent.layui.layer.zIndex,
      iframe: url,
      end: function () {
        if (reload == 1) {
          window.parent.location.reload();
        } else if (reload == 2) {
          window.location.reload();
        }
        form.render('select');
      }
    })
  }

  window.HuiAdminShowBak = function (title, url, w, h, reload = 0) {
    if (title == null || title == '') {
      title = false;
    }
    if (url == null || url == '') {
      url = "404.html";
    }
    if (w == null || w == '') {
      w = ($(window).width() * 0.9);
    }
    if (h == null || h == '') {
      h = ($(window).height() * 0.8);
    }
    $.get(url, function (res) {
      if (res.code == 0) {
        hui_msg(res.msg, 2);
        return false;
      }
      parent.layer.open({
        type: 2,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade: 0.4,
        title: title,
        content: url,
        end: function () {
          if (reload == 1) {
            window.parent.location.reload();
          } else if (reload == 2) {
            window.location.reload();
          }
          form.render('select');
        }
      });
    });
  }

  /**
   * 提示弹出
   */
  window.HuiAdminConfirm = function (url, msg = '真的要这样操作么？', reload = 0, data = {}) {
    layer.confirm(msg, {skin: 'skin-layer-hui'}, function (index) {
      var loading = layer.load(0);
      $.post(url, data, function (res) {
        layer.close(loading);
        if (res.code === 1 || res.code === 200) {
          layer.msg(res.msg, {icon: 1, time: 1500}, function () {
            if (reload == 1) {
              window.parent.location.reload();
            } else if (reload == 2) {
              window.location.reload();
            }
          });
        } else {
          layer.msg(res.msg, {icon: 2});
        }
      })
    });
  }

  /*删除弹出提示*/
  window.HuiAdminDel = function (url, msg = '真的要删除么？', reload = 0) {
    layer.confirm(msg, {skin: 'skin-layer-hui'}, function (index) {
      var loading = layer.load(0);
      $.post(url, function (res) {
        layer.close(loading);
        if (res.code === 1 || res.code === 200) {
          layer.msg(res.msg, {icon: 1, time: 1500}, function () {
            if (reload == 1) {
              window.location.reload();
            } else if (reload == 2) {
              window.location.reload();
            }
          });
        } else {
          layer.msg(res.msg, {icon: 2});
        }
      })
    });
  }
  //图片预览
  window.hui_img_preview = function (id, src) {
    if (src == '') return;
    layer.tips('<img src="' + htmlspecialchars(src) + '" height="100">', '#' + id, {
      tips: [1, '#fff']
    });
  }

  //关闭弹出层
  window.hui_close = function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
  }

  // 删除图片 (数据库已有的)
  window.fileItemDelete = function (id) {
    layer.confirm('您确定要删除该图片吗？', {
      title: '友情提示'
    }, function (index) {
      let picNums = parent.layui.$(".uploader-list").attr('data-nums');
      parent.layui.$(".uploader-list").attr('data-nums', parseInt(picNums) - 1);
      $('.file-item-id-' + id).remove();
      layer.close(index);
    });
  }

  /**
   *
   * @param table 数据
   * @param table_id 表格的id名
   * @param id_attr 要取id的字符串名
   * @returns {boolean|*}
   */
  window.table_get_ids = function (table, table_id, id_attr) {
    var checkStatus = table.checkStatus(table_id)
      , data = checkStatus.data;
    if (data.length < 1) {
      layer.msg('你没有选择任何数据', {icon: 2});
      return false;
    } else {
      var ids = [];
      for (var i = 0; i < data.length; i++) {
        ids += data[i][id_attr] + ',';
      }
      ids = ids.slice(0, -1);
      var arr = ids.split(',');
      for (var i in arr) {
        (arr[i])
      }
      return arr;
    }
  }

  /**
   * 选择图片回调
   * @param url
   * @param type
   * @param input_select_id
   */
  window.send_result_pic = function (url, type, input_select_id = '') {
    if (window.opener && window.opener.ckeditor_select_callback) {
      window.opener.ckeditor_select_callback(url, type, input_select_id);
    } else if (parent.ckeditor_select_callback) {
      parent.ckeditor_select_callback(url, type, input_select_id);
    } else {
      copy(url)
      layer.alert('已复制文件地址：<span class="en-font">' + url + '</span>');
    }
    window.close();
  }

  window.copy = function (text) {
    var tag = document.createElement('input');
    tag.setAttribute('id', 'copyTextInput');
    tag.value = text;
    document.getElementsByTagName('body')[0].appendChild(tag);
    document.getElementById('copyTextInput').select();
    document.execCommand('copy');
    document.getElementById('copyTextInput').remove();
  }

});

/**
 * 封装msg消息
 * @param msg
 * @param msg_type 消息类型：1=成功；2=失败；3=.........
 * @param __function 回调函数
 */
function hui_msg(msg, msg_type = 1, __function = "") {
  layui.use(['layer', 'jquery'], function () {
    var layer = layui.layer;
    layer.msg(msg, {icon: msg_type, time: 1500}, __function);
  })
}

//html实体转换
function htmlspecialchars(str) {
  str = str.replace(/&/g, '&amp;');
  str = str.replace(/</g, '&lt;');
  str = str.replace(/>/g, '&gt;');
  str = str.replace(/"/g, '&quot;');
  str = str.replace(/'/g, '&#039;');
  return str;
}

function viewImage(imgUrl) {
  layer.open({
    type: 1,
    title: false,
    closeBtn: 0,
    scrollbar: false,
    skin: 'layui-layer-nobg', //没有背景色
    shadeClose: true,
    content: "<img style='max-width: 400px;max-height: 400px;' src='" + imgUrl + "'>"
  });
}

